Imports System.IO


Namespace Workflow


Public Class CTemplate

#Region "Members"
    Public Template As String
    Public StartTag As String = "["
    Public EndTag As String = "]"

    Private m_storage As String
#End Region

#Region "Constructor"
    Public Sub New(ByVal filePath As String)
        Me.New(Path.GetFileName(filePath), Path.GetDirectoryName(filePath))
    End Sub
    Public Sub New(ByVal fileName As String, ByVal folderPath As String)
        Template = ReadFile(folderPath, fileName)
        m_storage = Template
    End Sub
#End Region

#Region "Public Functions"
    Public Sub Reset()
        Template = m_storage
    End Sub
    Public Sub Replace(ByVal lookFor As String, ByVal replaceWith As String)
        Template = Microsoft.VisualBasic.Replace(Template, StartTag & lookFor & EndTag, replaceWith)
    End Sub
    Public Sub ReplaceRaw(ByVal lookFor As String, ByVal replaceWith As String)
        Template = Microsoft.VisualBasic.Replace(Template, lookFor, replaceWith)
    End Sub
#End Region

#Region "Shared Functions"
    Public Shared Function ReadFile(ByVal folderPath As String, ByVal fileName As String) As String
        If Not Directory.Exists(folderPath) Then
            If Not Directory.Exists(HttpContext.Current.Server.MapPath(folderPath)) Then
                Throw New Exception("ERROR: Folder '" & folderPath & "' does not exist")
            End If
            folderPath = HttpContext.Current.Server.MapPath(folderPath)
        End If

        Dim filePath As String = folderPath & fileName
        If Not File.Exists(filePath) Then
            filePath = folderPath & "\" & fileName
            If Not File.Exists(filePath) Then Throw New Exception("ERROR: File '" & filePath & "' does not exist")
        End If

        Dim fs As FileStream = File.OpenRead(filePath)
        Dim sr As New StreamReader(fs)
        ReadFile = sr.ReadToEnd()
        sr.Close()
    End Function
#End Region


End Class

End Namespace
